$(function(){
    var form = $('#J_form');

    window.UEDITOR_CONFIG.initialFrameHeight = 320;
    var ruleUe = UE.getEditor('J_rule');
    var detailUe = UE.getEditor('J_detail');

    // 开始时间
    var startDate = $('#J_start').datetimepicker({
        format: "yyyy-MM-dd hh:ii:ss",
        autoclose: true,
        todayBtn: true
    }).on('changeDate', function(ev) {
        var end = $('#J_end').val();
        var evDate = ev.date.getFullYear() + '-' + (ev.date.getMonth() + 1) + '-' + ev.date.getDate() + ' ' + ev.date.getHours() + ':' + (ev.date.getMinutes() + 5) + ':' + ev.date.getSeconds();
        if($.trim(end) != '') {
            var dt = new Date(end);
            if(ev.date.valueOf() > dt.valueOf()) {
                $('#J_end').val('');
            }
        }
        $('#J_end').datetimepicker('setStartDate', evDate);
    });

    var endDate = $('#J_end').datetimepicker({
        format: "yyyy-MM-dd hh:ii:ss",
        autoclose: true,
        todayBtn: true
    }).on('changeDate', function(ev) {
        var end = $('#J_start').val();
        var expired = $('#J_expire').val();
        var evDate = ev.date.getFullYear() + '-' + (ev.date.getMonth() + 1) + '-' + ev.date.getDate()+ ' ' + ev.date.getHours() + ':' + (ev.date.getMinutes() - 5) + ':' + ev.date.getSeconds();
        var expiredDate = ev.date.setMinutes(ev.date.getMinutes());

        if($.trim(end) != '') {
            var dt = new Date(end);

            if(ev.date.valueOf() < dt.valueOf()) {
                $('#J_start').val('');
            }
        }

        if($.trim(expired) != '') {
            var exp = new Date(expired);
            if(ev.date.valueOf() >= exp.valueOf()) {
                $('#J_expire').val($('#J_end').val());
            }
        } else {
            $('#J_expire').val($('#J_end').val());
        }
        $('#J_start').datetimepicker('setEndDate', evDate);
        $('#J_expire').datetimepicker('setStartDate', new Date(expiredDate));
    });

    if($('#J_expire').attr('readonly') != 'readonly') {
       var expireDate =  $('#J_expire').datetimepicker({
            format: "yyyy-MM-dd hh:ii:ss",
            autoclose: true,
            todayBtn: true
        });
    }




    function singleImageUpload(id, url, data, callbackFn){
        var filename = $("#" + id).val().split('/').pop().split('\\').pop();

        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(filename)) {
            alert('图片类型必须是.gif,jpeg,jpg,png中的一种');
            $("#" + id).val('');
            return false;
        }

        var options = {
            url: url +'?t=' + new Date(), //用于文件上传的服务器端请求地址
            secureuri: false, //是否需要安全协议，一般设置为false
            fileElementId: id, //文件上传域的ID
            data: data,
            dataType: 'json', //返回值类型 一般设置为json
            success:function(data, status){ //服务器成功响应处理函数
                callbackFn && callbackFn(data);
            },
            error: function(){
                layer.alert('上传图片请求失败，请重试！');
                return false;
            }
        };

        $.ajaxFileUpload(options);
    }

    $('input[type=text]').on('keypress', function() {
        $('input[type=text]').each(function(i, item){
            $(item).parent().removeClass('bad');
        });
    });

    $('body').off("change", '#J_upload_file').on('change', '#J_upload_file', function() {
        var id = $(this).attr('id');
        var $this = $(this);
        var data = {};
        data.id = $(this).attr('data-id') ? $(this).attr('data-id') : -1;

        singleImageUpload(id, ajaxUrl.img_upload_url, data, function(data) {
            if(data.status == 1) {
                var html = '<img src="'+ data.img +'" >' +
                    '<input type="hidden" value="'+ data.id +'" name="img" class="J_img_hideval">';
                $('#J_txt_btn').text('重新上传');
                $('#J_uploaded_img').empty().append(html);
            }

        });
    });


    function formValid() {

        function checkGoodsName() {
            var $gn = $('#J_goods_name'),
                goodsName = $.trim($gn.val());
            if(goodsName.length === 0) {
                showError($gn, '商品名不能为空');
                return false;
            }
            if(GLOBAL.base.charlen(goodsName) > 32) {
                showError($gn, '商品名长度大于16个中文字或32个英文字');
                return false;
            }

            hideError($gn);
            return true;
        }

        function checkScore() {
            var $sc = $('#J_score'),
                score = $.trim($sc.val());
            if(score.length === 0) {
                showError($sc, '积分不能为空');
                return false;
            }
            if(!/^[0-9]*[1-9][0-9]*$/.test(score)) {
                showError($sc, '积分输入不是正确的数字');
                return false;
            }
            hideError($sc);
            return true;
        }

        function checkMarketPirce() {
            var $mk = $('#J_market_price'),
                pri = $mk.val();
            if(pri.length > 0 && (parseFloat(pri) < 0.01 || !/^\d+(?:\.\d{1,2})?$/.test(pri))) {
                showError($mk, '价格输入不正确');
                return false;
            }
            hideError($mk);
            return true;
        }

        function checkNums() {
            var $cn = $('#J_nums'),
                score = $.trim($cn.val());
            if(score.length === 0) {
                showError($cn, '库存不能为空');
                return false;
            }
            if(!/^[0-9]*[1-9][0-9]*$/.test(score)) {
                showError($cn, '库存输入不正确');
                return false;
            }
            if(parseFloat(score) > 9999) {
                showError($cn, '库存量最大不超过9999');
                return false;
            }
            hideError($cn);
            return true;
        }

        function checkStartTime(){
            var $date = $('#J_start');
            if($.trim($date.val()).length === 0) {
                showError($date, '活动开始时间设置不正确');
                return false;
            }
            hideError($date);
            return true;
        }
        function checkendTime(){
            var $date = $('#J_end');
            if($.trim($date.val()).length === 0) {
                showError($date, '活动结束时间设置不正确');
                return false;
            }
            hideError($date);
            return true;
        }

        function checkExpireTime(){
            var $date = $('#J_expire');
            if($.trim($date.val()).length === 0) {
                showError($date, '券号失效时间设置不正确');
                return false;
            }
            hideError($date);
            return true;
        }

        function checkimg() {
            var $img = $('#J_uploaded_img').find('img');
            if($img.length === 0) {
                showError($img, '请上传商品图片');
                return false;
            }
            hideError($img);
            return true;
        }

        function checkduihuan() {
            var $limit = $('#J_limit_time'),
                limit = $.trim($limit.val());
            if(limit.length === 0) {
                showError($limit, '兑换限制不能为空');
                return false;
            }
            if(!/^[0-9]*[1-9][0-9]*$/.test(limit)) {
                showError($limit, '请输入大于0的整数');
                return false;
            }
            hideError($limit);
            return true;
        }
        function checkduihuanTotal() {
            var $limit = $('#J_limit_total'),
                limit = $.trim($limit.val());

            if(!/^[0-9]*$/.test(limit)) {
                showError($limit, '请输入大于等于0的整数');
                return false;
            }

            if(limit.length != 0 && parseInt(limit) !== 0 && parseInt(limit) < parseInt($('#J_limit_time').val())) {
                showError($limit, '总兑换次数限制必须大于等于每日兑换次数限制');
                return false;
            }
            hideError($limit);
            return true;
        }

        function checkRule() {
            var rule = ruleUe.getContent();
            if($.trim(rule).length === 0) {
                showError($('#J_rule'), '兑换规则不能为空');
                return false;
            }
            return true;
        }
        function checkDetail() {
            var rule = detailUe.getContent();
            if($.trim(rule).length === 0) {
                showError($('#J_rule'), '商品详情不能为空');
                return false;
            }
            return true;
        }

        function showError(obj, msg) {
            obj.focus().parent().addClass('bad');
            layer.msg(msg, {icon:2});
            /*new PNotify({
                text: msg,
                type: 'error'
            });*/
        }

        function hideError(obj) {
            obj.parent().removeClass('bad');
        }

        if(!checkGoodsName()) {
            return false;
        }

        if(!checkScore()) {
            return false;
        }

        if(!checkMarketPirce()) {
            return false;
        }
        if(!checkNums()) {
            return false;
        }
        if(!checkStartTime()) {
            return false;
        }
        if(!checkendTime()) {
            return false;
        }
        if(!checkExpireTime()) {
            return false;
        }
        if(!checkimg()) {
            return false;
        }
        if(!checkduihuan()) {
            return false;
        }
        if(!checkduihuanTotal()) {
            return false;
        }
        if(!checkRule()) {
            return false;
        }
        if(!checkDetail()) {
            return false;
        }

        return true;
    }



    $('#J_save').on('click', function(ev) {
        ev.preventDefault();

        if(formValid()) {
            $('#J_form').submit();
        }

        return false;
    });

    //保存到草稿
    $('#J_draft').on('click', function() {
        $.ajax({
            url: ajaxUrl.draft_url,
            type: 'post',
            data: form.serialize(),
            dataType: 'json',
            success: function(data) {
                if(data.status == 1) {
                    layer.alert('保存草稿箱成功',{icon: 1});
                } else {
                    layer.alert('保存草稿箱失败，请重试！',{icon: 2});
                    return false;
                }
            }
        })
    });

}());
